package com.dao;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import com.entity.User;

@Repository
public class UsersDaoImpl {
	@Resource
	private SessionFactory sessionFactory;
	
	//get、load查询方法是针对主键来说的，查询参数必须为主键；
	public User get(String id) {
		User user = this.sessionFactory.getCurrentSession().get(User.class, id);
		return user;
	}
	/*
	 * 修改信息
	 */
	public void update(User user){
		this.sessionFactory.getCurrentSession().update(user);
	}
	/*
	 * 注册
	 */
	public void save(User user){
		System.out.println("dao"+user);
		this.sessionFactory.getCurrentSession().save(user);
	}
	//get、load方法是针对主键来说，查询参数必须为主键；
	public User findByPhone(String phone){
		String hql="from User where phone=?";
		Query query=this.sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter(0, phone);
		User user = (User) query.uniqueResult();
		return user;
	}
	
	/*
	 * 注销账号
	 */
	public boolean userDel(User user){
		System.out.println("dao"+user);
		this.sessionFactory.getCurrentSession().delete(user);
		if(user==null){
			return true;
		}else{
			return false;
		}
	}
	
	/*
	 *登录
	 *按phone+password
	 */
	public boolean Login(String phone,String password){
		User u = null;
		String hql="from User u where u.phone=? and u.password=?";
		try{
			Query query=this.sessionFactory.getCurrentSession().createQuery(hql);
			query.setParameter(0, phone);
			query.setParameter(1, password);
			u = (User) query.uniqueResult();
			
		}catch (Exception e){
			e.printStackTrace();
		}
		if (u != null) {
			return true;
		} else {
			return false;
		}
		
	}
	
	//通过Phone找用户
	public User getUserByPhone(String phone){
		User user = null;
		String hql = "from User u where u.phone=?";
		try{
			Query query=this.sessionFactory.getCurrentSession().createQuery(hql);
			query.setParameter(0,phone);
			user = (User) query.uniqueResult();
			System.out.println("查询出的用户是"+user);
			return user;
		}catch (Exception e){
			e.printStackTrace();
			return null;
		}
	}
	public boolean getByPhone(String phone){
		User u = null;
		String hql = "from User u where u.phone=?";
		try{
			Query query=this.sessionFactory.getCurrentSession().createQuery(hql);
			query.setParameter(0, phone);
			u = (User) query.uniqueResult();
		}catch (Exception e){
			e.printStackTrace();
		}
		if(u!=null){
			return true;
		}else{
			return false;
		}
	}
	
	
	

}
